package com.cnzha.zk;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhaoxin
 * @email: zdkk@foxmail.com
 * @Date: 2020/4/7 23:30
 */
public class DistrinuteClient {


    public static final String clust = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    public static final int sessionTimeOut = 2000;
    private String parentNode = "/servers";
    private ZooKeeper zooKeeper;

    public void init() throws IOException {
        zooKeeper = new ZooKeeper(clust, sessionTimeOut, (watchedEvent) -> {
            //process回调
            Watcher.Event.EventType type = watchedEvent.getType();
            String path = watchedEvent.getPath();
            System.out.println("path = " + path);
            System.out.println("type = " + type);
            //再次启动监听
            try {
                getServerList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    // 获取服务器列表信息
    public void getServerList() throws Exception {

        // 1获取服务器子节点信息，并且对父节点进行监听
        List<String> children = zooKeeper.getChildren(parentNode, true);
        // 2存储服务器信息列表
        ArrayList<String> servers = new ArrayList<>();
        // 3遍历所有节点，获取节点中的主机名称信息
        for (String child : children) {
            byte[] data = zooKeeper.getData(parentNode + "/" + child, false, null);
            servers.add(new String(data));
        }
        // 4打印服务器列表信息
        System.out.println(servers);
    }

    // 业务功能
    public void business() throws Exception {
        System.out.println("client is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        DistrinuteClient distrinuteClient = new DistrinuteClient();
        distrinuteClient.init();
        distrinuteClient.getServerList();
        distrinuteClient.business();
    }


}
